﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;


namespace WebLicenseGenerator.UC
{
	public partial class MaskedCNPJ : System.Web.UI.UserControl
	{
		bool _validateEmptyCNPJ = true;

		public bool ValidateEmptyCNPJ
		{
			get { return _validateEmptyCNPJ; }
			set { _validateEmptyCNPJ = value; }
		}
		public string Text
		{
			get
			{
				if(mskTxt.Text == "__.___.___/____-__")
					return String.Empty;
				else
					return mskTxt.Text;
			}

			set { mskTxt.Text = value; }
		}
		public string Number
		{
			get { return mskTxt.Text.Replace("_","").Replace(".","").Replace("/","").Replace("-",""); }
		}
		public bool IsEmpty
		{
			get { return (String.IsNullOrEmpty(this.Text)); }
		}
		public bool IsEnabled
		{
			get { return mskTxt.Enabled; }
			set { mskTxt.Enabled = value; }
		}
		public bool IsValid
		{
			get
			{
				cvInvalidCNPJ.Validate();

				if (ValidateEmptyCNPJ)
				{
					cvBlankCNPJ.Validate();
					return (cvBlankCNPJ.IsValid && cvInvalidCNPJ.IsValid);
				}
				else
					return (cvInvalidCNPJ.IsValid);
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{
		}

		protected void ValidateBlankCNPJ(object sender, ServerValidateEventArgs args)
		{
			args.IsValid = !(this.ValidateEmptyCNPJ && String.IsNullOrEmpty(this.Text));
		}

		protected void ValidateInvalidCNPJ(object sender, ServerValidateEventArgs args)
		{
			if (!this.IsEmpty)
				args.IsValid = ValidateCNPJ();
			else
				args.IsValid = true;
		}

		bool ValidateCNPJ()
		{
			int[] Multiplicador1 = new int[12] { 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2 };
			int[] Multiplicador2 = new int[13] { 6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2 };
			int Soma;
			int Resto;
			string Digito;
			string TempCNPJ;
			string cnpj;

			cnpj = this.Text.Replace(".", "").Replace("-", "").Replace("/", "").Replace("_","");

			if (cnpj.Length != 14)
				return false;

			TempCNPJ = cnpj.Substring(0, 12);

			Soma = 0;
			for (int i = 0; i < 12; i++)
				Soma += int.Parse(TempCNPJ[i].ToString()) * Multiplicador1[i];

			Resto = (Soma % 11);
			if (Resto < 2)
				Resto = 0;
			else
				Resto = 11 - Resto;

			Digito = Resto.ToString();

			TempCNPJ = TempCNPJ + Digito;
			Soma = 0;
			for (int i = 0; i < 13; i++)
				Soma += int.Parse(TempCNPJ[i].ToString()) * Multiplicador2[i];

			Resto = (Soma % 11);
			if (Resto < 2)
				Resto = 0;
			else
				Resto = 11 - Resto;

			Digito = Digito + Resto.ToString();

			return cnpj.EndsWith(Digito);
		}
	}
}